package filter;

import com.sun.deploy.net.HttpRequest;
import entity.Msg;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "AdminFilter")
public class AdminFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)resp;
        String url = request.getRequestURI();
//        System.out.println(url);
        String[] urlParts = url.split("/");
        String key = urlParts[urlParts.length - 1];
        String key2 = urlParts[urlParts.length - 2];
        if ("login.html".equals(key) || "css".equals(key2) || "font".equals(key2) || "images".equals(key2) ||
            "js".equals(key2) || "json".equals(key2)) {
            chain.doFilter(req, resp);
        } else {
            Cookie[] cookies = request.getCookies();
            boolean isLogin = false;
            boolean isAdmin = false;
            if (cookies != null) {
                for (Cookie c:cookies) {
                    if ("uid".equals(c.getName()) && Integer.parseInt(c.getValue()) > 0) {
                        isLogin = true;
                    } else if ("ad".equals(c.getName()) && Integer.parseInt(c.getValue()) == 65535) {
                        isAdmin = true;
                    }
                }
            }
            if (isLogin && isAdmin) {
                chain.doFilter(req, resp);
            } else {
                response.sendRedirect("login.html");
            }
        }

    }

    public void init(FilterConfig config) throws ServletException {

    }

}
